<?php



namespace app\admin\controller;

use app\admin\service\NodeService;
use app\common\model\ShopStore;
use app\common\service\Sms;
use library\Controller;
use think\captcha\Captcha;
use think\Db;
use think\facade\Request;
use think\facade\Url;

/**
 * 用户登录管理
 * Class Login
 * @package app\admin\controller
 */
class Login extends Controller
{

    /**
     * 后台登录入口
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        if (Request::isGet()) {
            if (NodeService::islogin()) {
                $this->redirect('@admin');
            } else {
                $this->domain = Request::host(true);
                $this->devmode = in_array($this->domain, ['127.0.0.1', 'localhost']) or stripos($this->domain, 'thinkadmin.top') <> false;
                if (!($this->loginskey = session('loginskey'))) session('loginskey', $this->loginskey = uniqid());
                $this->title = '系统登录';
                $this->fetch();
            }
        } else {
            $data = $this->_input([
                'username' => input('username'), 'password' => input('password'),
            ], [
                'username' => 'require|min:4', 'password' => 'require|min:4',
            ], [
                'username.require' => '登录账号不能为空！',
                'password.require' => '登录密码不能为空！',
                'username.min'     => '登录账号长度不能少于4位有效字符！',
                'password.min'     => '登录密码长度不能少于4位有效字符！',
            ]);
            // 用户信息验证
            $map = ['is_deleted' => '0', 'username' => $data['username']];
            $user = Db::name('SystemUser')->where($map)->order('id desc')->find();
            if (empty($user)) $this->error('登录账号或密码错误，请重新输入!');
            //验证码验证
            if(!config('app_debug')){
                if(!captcha_check($this->request->post('verifyCode'))){
                    $this->error('验证码错误，请重新输入!');
                };
            }
            if ($user['password'] !== md5($data['password'])) {
                if (empty($cache) || empty($cache['time']) || empty($cache['number']) || $cache['time'] + 3600 < time()) {
                    $cache = ['time' => time(), 'number' => 1, 'geoip' => $this->request->ip()];
                } elseif ($cache['number'] + 1 <= 10) {
                    $cache = ['time' => time(), 'number' => $cache['number'] + 1, 'geoip' => $this->request->ip()];
                }
                cache("user_login_{$user['username']}", $cache);
                if (($diff = 10 - $cache['number']) > 0) {
                    $this->error("<strong class='color-red'>登录账号或密码错误！</strong><p class='nowrap'>还有 {$diff} 次尝试机会，将锁定一小时内禁止登录！</p>");
                } else {
                    sysoplog('系统管理', "账号{$user['username']}连续10次登录密码错误，请注意账号安全！");
                    $this->error("<strong class='color-red'>登录账号或密码错误！</strong><p class='nowrap'>尝试次数达到上限，锁定一小时内禁止登录！</p>");
                }
            }
            if (empty($user['status'])) $this->error('账号已经被禁用，请联系管理员!');
            // 账号锁定消息
            $cache = cache("user_login_{$user['username']}");
            if (is_array($cache) && !empty($cache['number']) && !empty($cache['time'])) {
                if ($cache['number'] >= 10 && ($diff = $cache['time'] + 3600 - time()) > 0) {
                    list($m, $s, $info) = [floor($diff / 60), floor($diff % 60), ''];
                    if ($m > 0) $info = "{$m} 分";
                    $this->error("<strong class='color-red'>抱歉，该账号已经被锁定！</strong><p class='nowrap'>连续 10 次登录错误，请 {$info} {$s} 秒后再登录！</p>");
                }
            }
            $store = ShopStore::where('admin_id',$user['id'])->where('status',1)->with(['systemuser'])->find();
            // 登录成功并更新账号
            cache("user_login_{$user['username']}", null);
            Db::name('SystemUser')->where(['id' => $user['id']])->update([
                'login_at'  => Db::raw('now()'),
                'login_ip'  => $this->request->ip(),
                'login_num' => Db::raw('login_num+1'),
            ]);
            session('loginskey', null);
            session('admin_user', $user);
            NodeService::applyUserAuth(true);
            if ($store){
                session('store',$store);
            }else{
                $staff = Db::name('shop_store_staff')->where('admin_id',$user['id'])->where('status',1)->find();
                if ($staff){
                    $store = [
                        'id' => $staff['store_id'],
                        'staff_id' => $staff['id']
                    ];
                    session('store',$store);
                }else{
                    session('store',[]);
                }
            }
            sysoplog('系统管理', '用户登录系统成功');
            $this->success('登录成功，正在进入系统...', url('@admin'));
        }
    }
    public function adminSmsLogin(){
        $data = $this->_input([
            'phone' => input('phone'), 'code' => input('code'),
        ], [
            'phone' => 'require|mobile', 'code' => 'require|number|min:6',
        ], [
            'phone.require' => '登录手机号不能为空！',
            'code.require' => '验证码不能为空！',
            'code.number' => '请输入6位数验证码！',
            'code.min' => '请输入6位数验证码！',
        ]);
        // 用户信息验证
        $map = ['is_deleted' => '0', 'phone' => $data['phone']];
        $user = Db::name('SystemUser')->where($map)->order('id desc')->find();
        if (empty($user)) $this->error('此手机号暂未绑定任何管理员，请重新输入!');
        $res = Sms::check($data['phone'],$data['code'],10);
        if(!$res){
            $this->error('验证码错误，请重新输入!');
        }
        if (empty($user['status'])) $this->error('账号已经被禁用，请联系管理员!');
        // 账号锁定消息
        $cache = cache("user_login_{$user['username']}");
        if (is_array($cache) && !empty($cache['number']) && !empty($cache['time'])) {
            if ($cache['number'] >= 10 && ($diff = $cache['time'] + 3600 - time()) > 0) {
                list($m, $s, $info) = [floor($diff / 60), floor($diff % 60), ''];
                if ($m > 0) $info = "{$m} 分";
                $this->error("<strong class='color-red'>抱歉，该账号已经被锁定！</strong><p class='nowrap'>连续 10 次登录错误，请 {$info} {$s} 秒后再登录！</p>");
            }
        }

        // 登录成功并更新账号
        cache("user_login_{$user['username']}", null);
        Db::name('SystemUser')->where(['id' => $user['id']])->update([
            'login_at'  => Db::raw('now()'),
            'login_ip'  => $this->request->ip(),
            'login_num' => Db::raw('login_num+1'),
        ]);
        session('loginskey', null);
        session('admin_user', $user);
        NodeService::applyUserAuth(true);
        sysoplog('系统管理', '用户登录系统成功');
        $this->success('登录成功，正在进入系统...', url('@admin'));
    }
    /**
     * 退出登录
     */
    public function out()
    {
        \think\facade\Session::clear();
        \think\facade\Session::destroy();
        $this->success('退出登录成功！', url('@admin/login'));
    }

    /**
     * 获取验证码
     * @Author: rocky
     * 2020/2/26 15:29
     */
    public function sendAdminLoginSms(){
        $phone = $this->request->post('phone');
        $map = ['is_deleted' => '0', 'phone' => $phone];
        $user = Db::name('SystemUser')->where($map)->order('id desc')->find();
        if (empty($user)) $this->error('此手机号暂未绑定任何管理员，请重新输入!');
        $res = Sms::sendRandNumber($phone,6,10,'后台登录',false);
        if($res === true){
            $this->success('发送成功');
        }else{
            $this->error($res);
        }
    }

    /**
     * 验证码
     * @Author: rocky
     * 2020/2/27 9:38
     * @return \think\Response
     */
    public function captcha(){
        ob_clean();
        $config = [
            'imageW'   =>120,
            'imageH'   => 34,
            'length'   => 4,
            'fontSize' => 16,
            'useCurve' => false,
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }
}
